﻿using MediatR;
using Swork03_28.Api.Application.Commands.TraceableCommand;
using Swork03_28.Services.Interface;
using Swork03_28.Domain;
using Swork03_28.Domain.TraceableInfos;

namespace Swork03_28.Api.Application.CommandHandlers.TraceableHandler
{
    public class TraceableUpdateCommandHandler : IRequestHandler<TraceableUpdateCommand, int>
    {
        private readonly ITraceableService traceableService;

        public TraceableUpdateCommandHandler(ITraceableService traceableService)
        {
            this.traceableService = traceableService;
        }

        public async Task<int> Handle(TraceableUpdateCommand request, CancellationToken cancellationToken)
        {
            var only = traceableService.GetValues(x => x.Batch == request.Batch && x.Id != request.Id).Result.FirstOrDefault();
            if (only != null)
            {
                //同一批次下该商品已存在
                return -1;
            }
            return await traceableService.UpdateAsync(new Traceables()
            {
                Batch = request.Batch,
                CreatePeople = request.CreatePeople,
                CreateTime = request.CreateTime,
                Gid = request.Gid,
                Id = request.Id,
                Images = request.Images,
                IsDel = request.IsDel,
                Number = request.Number,
                ProduceEnterprise = request.ProduceEnterprise,
                Shelflife = request.Shelflife,
                UpdateePeople = "李四",
                UpdateTime = DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
            });
        }
    }
}
